const { Service } = require('egg')
// const { tableToList } = require('../utils/tools');
const cheerio = require('cheerio')

module.exports = class SinfoService extends Service {
  /**
   * * 学籍卡片信息
   * @return {Object} *
   */
  async table() {
    const Cookie = this.ctx.state.Cookie
    const apiUrl = `${this.ctx.state.baseUrl}/jwglxt/xsxxxggl/xsgrxxwh_cxXsgrxx.html?gnmkdm=N100801&layout=default`
    const res = await this.ctx.curl(apiUrl, {
      // method: 'POST',
      method: 'GET',
      // data: {
      //   gnmkdm: 'N100801',
      //   layout: 'default',
      // },
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        Host: 'jw.hieu.edu.cn',
        Origin: 'http://jw.hieu.edu.cn',
      },
      timeout: 10000,
    })
    const info = {}
    // console.log('res.status', res.status);
    // console.log('res', res);
    if (res.status === 200) {
      try {
        const pageXml = res.data.toString()
        const $ = cheerio.load(pageXml)
        // 拿到数据存于数组dataList
        const dataList = [
          $('#col_jg_id').text().replace(/\s/g, ''),
          $('#col_zyh_id').text().replace(/\s/g, ''),
          $('#col_xz').text().replace(/\s/g, ''),
          $('#col_bh_id').text().replace(/\s/g, ''),
          $('#col_xh').text().replace(/\s/g, ''),
          $('#col_xm').text().replace(/\s/g, ''),
          $('#col_xbm').text().replace(/\s/g, ''),
          $('#col_njdm_id').text().replace(/\s/g, ''),
        ]
        const tableList = ['院系', '专业', '学制', '班级', '学号', '姓名', '性别', '年级']
        // 键值对处理
        const result = {}
        tableList.forEach((key, i) => {
          const value = dataList[i]
          result[key] = value
        })
        return result
      } catch (err) {
        console.log('err', err)
        throw err
      }
    }
    return info
  }
}
